package com.ccl.controller.client;

import com.ccl.entity.ResponseData;
import com.ccl.entity.User;
import com.ccl.service.UserService;
import com.ccl.service.impl.SmsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
public class UserController {
    @Autowired
    private SmsServiceImpl smsService;
    @Autowired
    private UserService userService;
    //跳转到注册页面
    @RequestMapping("/toRegister")
    public String toRegister(){
        return "comm/myregister";
    }

    //发送短信验证码
    @RequestMapping("/sendSms")
    @ResponseBody
    public ResponseData sendSms(HttpServletRequest request,String tel) throws Exception {
        System.out.println("tel="+tel);
        //将短信发送给指定的手机号：短信服务
        String code = smsService.sendSms("18063117540");
        //保存当前验证码，在登录的时候进行验证
        request.getSession().setAttribute("checkCode",code);
        System.out.println("短信验证码发送成功");
        return ResponseData.OK();
    }

    //注册
    @RequestMapping("/register")
//    @ResponseBody
    public String register(HttpServletRequest request){
        //获取注册数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String checkCode = request.getParameter("checkCode");
        //判断手机号是否存在
        boolean b = userService.isExist(username);
        if (b){
            //手机号已经存在,不能注册成功
            request.setAttribute("errTel","手机号已经注册，请重新输入");
            //回到注册页面
           return "comm/myregister";
        }
        //判断短信验证码是否正确
        String code = (String) request.getSession().getAttribute("checkCode");
        if (code==null || !code.equals(checkCode)){
            //验证码不正确
            request.setAttribute("errCheckCode","短信验证码有误，请重新发送!");
            //回到注册也面
            return "comm/myregister";
        }
        //数据正确，添加用户
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        userService.registerUser(user);
        //清空短信验证码
        request.getSession().removeAttribute("checkCode");
        return "comm/login";//跳转到登录页面
    }
}
